<template>
  <view class="flex-col">

    <car-info :value="form"></car-info>

    <view class="page-wrap" :class="canEdit?'bottom115':''">

      <view class="lineBottom10 page-section">
        <uni-section title="GPS安装信息" type="line"/>
      </view>

      <uni-forms ref="form" :value="form" labelWidth="auto" :labelPosition="canEdit?'top':'left'">

        <uni-forms-item label="GPS是否免安装:" name="isNoInstall" :required="canEdit" :rules="[{
                                         required: true,
                                         errorMessage: '请选择GPS是否免安装',
                                         validateTrigger: 'bind'
                                       }]">
          <uni-data-checkbox v-if="canEdit" v-model="form.isNoInstall"
                             :localdata="[{text: '否',value: 0}, {text: '是',value: 1}]"/>
          <text v-else class="text-value">{{0 == form.isNoInstall ? '否' : 1 == form.isNoInstall ? '是' : '--'}}
          </text>
        </uni-forms-item>

        <template v-if="0==form.isNoInstall">
          <uni-forms-item :required="canEdit" name="installTime" label="预约安装时间:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择预约安装时间',
                                         validateTrigger: 'bind'
                                       }]">
            <uni-datetime-picker v-if="canEdit" type="datetime" return-type="string" v-model="form.installTime"/>
            <text v-else class="text-value">{{ form.installTime|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="installAddress" label="安装地点:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择安装地点',
                                         validateTrigger: 'bind'
                                       }]">
            <province-city-district v-if="canEdit" v-model="form.installAddressCode" @change="citySelectionChange"></province-city-district>
            <text v-else class="text-value">{{ form.installAddress|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="installAddressInfo" label="安装具体地址:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入安装具体地址',
                                         validateTrigger: 'blur'
                                       }]">
            <uni-easyinput v-if="canEdit" type="text" v-model="form.installAddressInfo" placeholder="请输入安装具体地址"/>
            <text v-else class="text-value">{{ form.installAddressInfo|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="gpsBrand" label="GPS品牌:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择GPS品牌',
                                         validateTrigger: 'bind'
                                       }]">
            <zxz-uni-data-select
              v-model="form.gpsBrand"
              dataKey="label"
              dataValue="value"
              v-if="canEdit"
              :localdata="dict.type.gps_brand_list"></zxz-uni-data-select>
            <dict-tag v-else
                      :options="dict.type.gps_brand_list"
                      :value="form.gpsBrand"/>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="gpsPrice" label="GPS金额:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入GPS金额',
                                         validateTrigger: 'blur'
                                       }]">
            <uni-easyinput v-if="canEdit" @input="inputChange" type="digit" maxlength="12" v-model="form.gpsPrice"
                           placeholder="请输入GPS金额"/>
            <text v-else class="text-value">{{ form.gpsPrice|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item v-if="isList" :required="canEdit" name="totalAmount" label="合计GPS金额:" :rules="[{
                                         required: true,
                                         errorMessage: '系统根据批量车辆数量*GPS金额计算',
                                         validateTrigger: 'blur'
                                       }]">
            <uni-easyinput v-if="canEdit" disabled type="digit" maxlength="12" v-model="form.totalAmount"
                           placeholder="系统根据批量车辆数量*GPS金额计算"/>
            <text v-else class="text-value">{{ form.totalAmount|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="equipmentType" label="设备类型:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择设备类型',
                                         validateTrigger: 'bind'
                                       }]">
            <zxz-uni-data-select
              v-model="form.equipmentType"
              dataKey="label"
              dataValue="value"
              v-if="canEdit"
              :localdata="dict.type.gps_device_type"></zxz-uni-data-select>
            <dict-tag v-else
                      :options="dict.type.gps_device_type"
                      :value="form.equipmentType"/>
          </uni-forms-item>

          <uni-forms-item v-if="1 == form.equipmentType || 3 == form.equipmentType"
                          name="wiredCount" label="有线个数:">
            <zxz-uni-data-select
              v-model="form.wiredCount"
              @input="inputChange"
              dataKey="name"
              dataValue="value"
              v-if="canEdit"
              :localdata="installNum"></zxz-uni-data-select>
            <text v-else class="text-value">{{ form.wiredCount|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item v-if="2 == form.equipmentType || 3 == form.equipmentType"
                          name="wirelessCount" label="无线个数:">
            <zxz-uni-data-select
              v-model="form.wirelessCount"
              @input="inputChange"
              dataKey="name"
              dataValue="value"
              v-if="canEdit"
              :localdata="installNum"></zxz-uni-data-select>
            <text v-else class="text-value">{{ form.wirelessCount|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item v-if="isList && (1 == form.equipmentType || 3 == form.equipmentType)" name="wiredTotalCount" label="合计有线设备数量:">
            <uni-easyinput v-if="canEdit" disabled type="digit" maxlength="12" v-model="form.wiredTotalCount"
                           placeholder="系统根据批量车辆数量*有线安装数量计算"/>
            <text v-else class="text-value">{{ form.wiredTotalCount|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item v-if="isList && (2 == form.equipmentType || 3 == form.equipmentType)" name="wirelessTotalCount" label="合计无线设备数量:">
            <uni-easyinput v-if="canEdit" disabled type="digit" maxlength="12" v-model="form.wirelessTotalCount"
                           placeholder="系统根据批量车辆数量*无线安装数量计算"/>
            <text v-else class="text-value">{{ form.wirelessTotalCount|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="sceneContacts" label="现场联系人:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入现场联系人',
                                         validateTrigger: 'blur'
                                       }]">
            <uni-easyinput v-if="canEdit" type="text" v-model="form.sceneContacts" placeholder="请输入现场联系人"/>
            <text v-else class="text-value">{{ form.sceneContacts|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="sceneContactsTel" label="现场联系人电话:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入现场联系人电话',
                                         validateTrigger: 'blur'
                                       }]">
            <uni-easyinput v-if="canEdit" type="number" maxlength="12" v-model="form.sceneContactsTel"
                           placeholder="请输入现场联系人电话"/>
            <text v-else class="text-value">{{ form.sceneContactsTel|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item :required="canEdit" name="gpsServicePeriod" label="GPS设备服务期限:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择GPS设备服务期限',
                                         validateTrigger: 'bind'
                                       }]">
            <zxz-uni-data-select
              v-model="form.gpsServicePeriod"
              dataKey="name"
              dataValue="value"
              v-if="canEdit"
              :localdata="periodNum"></zxz-uni-data-select>
            <text v-else class="text-value">{{ form.gpsServicePeriod|filterNull }}</text>
          </uni-forms-item>

          <uni-forms-item name="imageOss" label="上传照片:">
          </uni-forms-item>
          <image-common :disabled="!canEdit" :up-type="0" v-model="form.imageOss"></image-common>

          <uni-forms-item name="remark" label="备注:">
            <uni-easyinput v-if="canEdit" type="textarea" maxlength="200" v-model="form.remark"
                           placeholder="请输入备注"/>
            <text v-else class="text-value">{{ form.remark|filterNull }}</text>
          </uni-forms-item>
        </template>

        <uni-forms-item v-if="1==form.isNoInstall"
          :required="canEdit" name="noInstallProveId" :label="canEdit?'上传免安装证明:':'查看免安装证明:'"
            :rules="[{
                       required: true,
                       errorMessage: '请上传照片',
                       validateTrigger: 'bind'
                     }]">
        </uni-forms-item>
        <image-common v-if="1==form.isNoInstall" :disabled="!canEdit" :up-type="2" v-model="form.noInstallProveId"></image-common>

      </uni-forms>

    </view>

    <exam-flow v-if="!canEdit && form.flowId" :instanceId="form.flowId">
    </exam-flow>
    <view class="button-container" v-if="canEdit">
      <button class="btn-item" @click="submit">提 交</button>
    </view>
  </view>
</template>

<script>

import CarInfo from "@/pages/CarPage/gps/components/carInfo.vue";
import {carWorkOrderInfo, saveCarGpsInstall, gpsInstall} from "@/api/gps/gpsList"
import UniSection from "@/uni_modules/uni-section/components/uni-section/uni-section.vue";
import ProvinceCityDistrict from "@/pages/CarPage/gps/components/provinceCityDistrict.vue";

export default {
  components: {ProvinceCityDistrict, UniSection, CarInfo},
  dicts: ["gps_brand_list", "gps_device_type"],
  data() {
    return {
      form: {},
      state: 'write',
      carIds: null,
      installNum:[
        {
          name:"1",
          value:1
        },
        {
          name:"2",
          value:2
        },
        {
          name:"3",
          value:3
        },
        {
          name:"4",
          value:4
        },
        {
          name:"5",
          value:5
        }
      ],
      periodNum:[{
          name:"1年",
          value:"1年"
        },
        {
          name:"2年",
          value:"2年"
        },
        {
          name:"3年",
          value:"3年"
        }]
    }
  },
  computed: {
    canEdit() {
      return 'write' === this.state;
    },
    isList(){
      return this.form.carList !== undefined && this.form.carList !== null && this.form.carList.length>0;
    }
  },
  onLoad(op) {
    console.log('op', op);
    this.state = op?.state ?? 'write';
    this.carIds = op?.carIds ?? null;

    let title = this.canEdit?'安装工单申请':'安装工单详情';
    if (this.carIds) {
      this.getOldData();
    }
    uni.setNavigationBarTitle({
      title
    })
  },
  methods: {
    inputChange() {
      if(this.form.carList && this.form.carList.length>0){
        let num = this.form.carList.length;
        if (this.form.gpsPrice && num) {
          this.$set(this.form, 'totalAmount', (Number(this.form.gpsPrice) * num).toFixed(2))
        } else {
          this.$set(this.form, 'totalAmount', null)
        }

        if(this.form.wiredCount){
          this.$set(this.form, 'wiredTotalCount', Number(Number(this.form.wiredCount) * num))
        }else {
          this.$set(this.form, 'wiredTotalCount', null)
        }

        if(this.form.wirelessCount){
          this.$set(this.form, 'wirelessTotalCount', Number(Number(this.form.wirelessCount) * num))
        }else {
          this.$set(this.form, 'wirelessTotalCount', null)
        }

        // console.log(this.form)
        this.$forceUpdate()
      }
    },
    citySelectionChange(val) {
      console.log('val', val);
      if (val && val.length>0) {
        this.form.installAddressCode = val.map(item=>item.value).join(",");
        this.form.installAddress = val.map(item=>item.text).join("");
      } else {
        this.form.installAddressCode = "";
        this.form.installAddress = null;
      }
      this.$forceUpdate();
    },
    getOldData() {
      carWorkOrderInfo({carIds: this.carIds, workOrderType: 12}).then(res => {
        let intentList = res.data;
        console.log('接到', intentList)

        if (intentList !== undefined && intentList !== null && intentList.length > 0) {
          if (intentList[0].businessDataId !== undefined && intentList[0].businessDataId !== null && intentList[0].businessDataId != '') {
            //提报过，请求详情
            if (intentList.length > 1) {
              //大于1，显示表格
              this.$set(this.form, 'carList', intentList)
            }
            this.initData(intentList[0].businessDataId)
          } else {
            if (intentList.length > 1) {
              //大于1，显示表格
              this.$set(this.form, 'carList', intentList)
            } else {
              //详情单个详情
              this.form = {...this.form, ...intentList[0]}

              // this.form = {"id":"1792446711469486082","purchaseOrderId":"1790289090985701377","carId":"1792446711096193025","inspectionLastTime":null,"flowId":null,"businessDataId":null,"ascription":"近多出行","ascriptionId":100,"provinceName":"北京市","cityName":"北京市","region":"西北地区","operationsName":"天津","propertyRightName":"近多出行","brandName":"奥迪","modelName":"2023款 奥迪A4L 45 TFSI quattro 臻选动感型","seriesName":"奥迪A4L","carNo":null,"vinNo":"FOWU1000046044","businessType":"2","customerName":"极易净水科技(上海)有限公司","customerId":"1782978493934555137","workOrderCode":"GPS20240520144612000001","contractType":0,"contractStartTime":null,"contractEndTime":null,"workOrderType":12,"workOrderStatus":1,"contractReportNumber":"DDCT20240514105214000003","procurementReportNumber":"NCQCG-20240514155235000001","processedByTime":null,"processedByName":null,"workOrderNumber":"","insuranceWorkType":null,"orderCode":"DD20240514105210000003","orderId":"1790213489591345153","carRegisterTime":null,"seatNumber":"5","fuelType":null,"rentNum":null,"carType":null,"carNature":null,"createTime":"2024-05-20 14:46:13","updateTime":"2024-05-20 14:46:13","overdueDuration":null,"lastInspectionTime":null,"inspectionStatus":null,"insuranceChannels":null,"policyCode":null,"insuranceCompany":null,"insuranceCompanyId":null,"policyValidity":null,"actualEndTime":null,"totalAmount":null,"brandId":null,"seriesId":null,"modelId":null,"flowBusinessId":null,"processedById":null,"expenseStatus":null,"jqxCompany":null,"syxActualBeginTime":null,"syxCompany":null,"jqxActualBeginTime":null,"jqxActualEndTime":null,"syxActualEndTime":null,"purchaseSource":"2","mainOrderNo":"DDCL20240514105210000003","auditStatus":null,"noInstallProveId":"1795346940418109441,1795346941659623426,1795346943391870978,1795359051743539201","gpsBrand":null,"equipmentNo":null,"sim":null,"equipmentType":null,"paymentTime":null,"paymentFlag":1,"isNoInstall":1,"contractNo":"DDCT20240514105214000003","purchaseNo":"NCQCG-20240514155235000001"}
            }
          }
        }
      })
    },
    initData(id) {
      uni.showLoading();
      gpsInstall(id)
        .then((res) => {
          if (res.code == 200) {
            let data = res.data;
            let carList = this.form.carList;
            this.form = {...this.form, ...data}
            this.$set(this.form, 'carList', carList)
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },

    submit() {
      this.form.contractNo = this.form.contractReportNumber;
      this.form.purchaseNo = this.form.procurementReportNumber;

      if (this.form.carList && this.form.carList.length > 0) {
        this.form.carIds = this.form.carList.map((item) => {
          return item.carId;
        });
        this.form.workIds = this.form.carList.map((item) => {
          return item.id;
        });

        // if(1==this.form.isNoInstall){
        //   //免安装
        //   let find = this.form.carList.find(item=>item.noInstallProveId===undefined||item.noInstallProveId===null||item.noInstallProveId===''||item.noInstallProveId===[]);
        //   if(find){
        //     this.$modal.msg("请上传免安装证明")
        //     return
        //   }
        // }

      } else {
        this.form.carIds = [this.form.carId];
        this.form.workIds = [this.form.id];
      }

      this.$refs.form.validate().then(res => {
        uni.showLoading();
        saveCarGpsInstall(this.form).then(response => {
          uni.hideLoading();
          uni.$emit("refreshGps", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000)
        }).finally(f => {
			setTimeout(() => {
			  uni.hideLoading();
			}, 1000)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
